<?php

namespace app\teacher\model;

use think\Model;
use app\common\model\Course as CourseModel;

class Course extends CourseModel
{
    public function getUpdateTimeAttr($value)
    {
        return $value ? date('Y.m.d H:i', $value) : '';
    }

    public function user()
    {
        return $this->hasOne(User::class, 'user_id', 'user_id')->field('user_id, nickname, avatar, mobile');
    }

    /**
     * 获取课次记录
     */
    public static function getCourses($teacherId, $date)
    {
        $teacherCourseId = TeacherCourse::getColumnByTeacherId($teacherId, 'teacher_course_id');
        $courses = self::getByDate($teacherCourseId, $date);
        $subCourse = self::getDateByMonth($teacherCourseId, $date);
        return [
            'courses' => self::lists($courses),
            'sub_course' => array_values(array_unique($subCourse))
        ];
    }

    /**
     * 获取某天记录
     */
    public static function getByDate($teacherCourseId, $date)
    {
        return self::with(['user', 'courseOrder'])->whereIn('teacher_course_id', $teacherCourseId)->whereIn('status', [3, 4])->where('date', $date)->order('time asc')->select();
    }

    /**
     * 获取已预约的时间
     */
    public static function getDateByMonth($teacherCourseId, $date = '')
    {
        $month = date('Y-m', strtotime($date));
        return self::whereIn('teacher_course_id', $teacherCourseId)->whereIn('status', [3, 4])->where('date', 'like', "{$month}%")->column('date');
    }

    public static function getFinishTimes($teacherCourseId)
    {
        return self::whereIn('teacher_course_id', $teacherCourseId)->where('status', 4)->column('time');
    }

    /**
     * 累积课时
     */
    public static function getHours($times)
    {
        $hour = 0;
        foreach ($times as $val) {
            if (!$val) {
                continue;
            }
            $hour += self::getHour($val);
        }
        return $hour;
    }

    /**
     * 获取教师的授课学生
     * @param $teacherId
     */
    public static function getStudents($teacherId)
    {
        $teacherCourseId = TeacherCourse::getColumnByTeacherId($teacherId, 'teacher_course_id');
        $userId = self::whereIn('teacher_course_id', $teacherCourseId)->whereIn('status', [2, 3,4])->column('user_id');
        return array_values(array_unique($userId));
    }

    /**
     * 累积天数
     */
    public static function getDays($teacherCourseId)
    {
        $days = self::whereIn('teacher_course_id', $teacherCourseId)->whereIn('status', 4)->column('date');
        return count(array_unique($days));
    }

    /**
     * 授课记录
     */
    public static function getFinishLog($teacherCourseId, $size = 20)
    {
        $courses = self::with(['user', 'teacherCourse' => function ($query) {
            $query->with('language');
        }])->whereIn('teacher_course_id', $teacherCourseId)->whereIn('status', 4)->order('updatetime desc')->paginate($size);
        return $courses;
    }

}
